import { isDef, isObject } from '@/utils/validate';

export function deepClone(obj) {
  if (!isDef(obj)) {
    return obj;
  }

  if (Array.isArray(obj)) {
    return obj.map((item) => deepClone(item));
  }

  if (isObject(obj)) {
    const to = {};
    Object.keys(obj).forEach((key) => {
      to[key] = deepClone(obj[key]);
    });

    return to;
  }
  return obj;
}

/**
 * 获取/assets/img文件夹下图片资源
 * @param name
 */
export const getAssetsImage = (name) => new URL(`/src/assets/img/${name}`, import.meta.url).href;

/**
 * 获取/assets/img文件夹下图片资源
 * @param name
 */
export const getAssetsDemoImage = (name) =>
  new URL(`/src/assets/demo/${name}`, import.meta.url).href;

/**
 * 格式化时间
 * @param date
 * @param format
 */
export const formatDate = function (date, format) {
  if (typeof date === 'string') date = new Date(date.replace(/-/g, '/'));
  if (typeof date === 'number') date = new Date(date);
  if (!format) format = 'yyyy-MM-dd';
  const dict = {
    yyyy: date.getFullYear(),
    M: date.getMonth() + 1,
    d: date.getDate(),
    H: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds(),
    MM: (date.getMonth() + 101).toString().substring(1),
    dd: (date.getDate() + 100).toString().substring(1),
    HH: (date.getHours() + 100).toString().substring(1),
    mm: (date.getMinutes() + 100).toString().substring(1),
    ss: (date.getSeconds() + 100).toString().substring(1),
    SSS: (date.getMilliseconds() + 1000).toString().substring(1)
  };

  return format.replace(/(yyyy|MM?|dd|HH?|mm?|ss?|SSS?)/g, function (sub) {
    if (
      sub === 'yyyy' ||
      sub === 'M' ||
      sub === 'd' ||
      sub === 'H' ||
      sub === 'm' ||
      sub === 's' ||
      sub === 'MM' ||
      sub === 'dd' ||
      sub === 'HH' ||
      sub === 'mm' ||
      sub === 'ss' ||
      sub === 'SSS'
    )
      return dict[sub].toString();
    else return '';
  });
};

/**
 * 进程睡眠
 * @param delay 睡眠时间
 */
export const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));

export const queryParam = (key) => {
  let url = location.toString();
  // 如果url中有特殊字符则需要进行一下解码
  url = decodeURI(url);
  const arrObj = url.split('?');
  if (arrObj.length > 1) {
    const arrPara = arrObj[1].split('&');
    let arr;
    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=');
      if (arr != null && arr[0] === key) {
        return decodeURIComponent(arr[1]);
      }
    }
    return '';
  } else {
    return '';
  }
};

export const queryUrlParam = (name) => {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  const r = window.location.href.split('?')[1].match(reg);
  if (r != null) return decodeURI(r[2]);
  return null;
};
